package com.xjk.encryp;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 许嘉凯
 */
public class AESUtil {

  /**
   * 生成AES加密的密钥
   *
   * @return SecretKey 返回生成的AES密钥
   * @throws Exception
   */
  public static SecretKey generateAESKey() throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(256); // 使用256位密钥
    return keyGenerator.generateKey();
  }

  /**
   * 将SecretKey对象转换为Base64字符串形式的密钥
   */
  public static String secretKeyToString(SecretKey secretKey) {
    return Base64.getEncoder().encodeToString(secretKey.getEncoded());
  }

  /**
   * 将Base64字符串形式的密钥转换为SecretKey对象
   *
   * @param keyString Base64编码的密钥字符串
   * @return SecretKey 返回SecretKey对象
   * @throws Exception
   */
  public static SecretKey stringToSecretKey(String keyString) throws Exception {
    byte[] decodedKey = Base64.getDecoder().decode(keyString);
    return new SecretKeySpec(decodedKey, "AES");
  }

  public static String encryptAES(String strToEncrypt, String secretKey) throws Exception {
    return encryptAES(strToEncrypt, stringToSecretKey(secretKey));
  }
  public static String decryptAES(String strToDecrypt, String secretKey) throws Exception {
    return decryptAES(strToDecrypt, stringToSecretKey(secretKey));
  }

      /**
       * 使用AES密钥对字符串进行加密
       *
       * @param strToEncrypt 要加密的字符串
       * @param secretKey    加密使用的AES密钥
       * @return String 加密后的字符串（Base64编码）
       * @throws Exception
       */
  public static String encryptAES(String strToEncrypt, SecretKey secretKey) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes());
    return Base64.getEncoder().encodeToString(encryptedBytes);
  }

  /**
   * 使用AES密钥对加密后的字符串进行解密
   *
   * @param strToDecrypt 要解密的字符串（Base64编码）
   * @param secretKey    解密使用的AES密钥
   * @return String 解密后的字符串
   * @throws Exception
   */
  public static String decryptAES(String strToDecrypt, SecretKey secretKey) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt));
    return new String(decryptedBytes);
  }


  public static void main(String[] args) throws Exception {
    // 待加密的原始文本
    String originalText = "sk-f777298ada8f4f8b8f92bf5b9c14ab04";
    // 生成AES密钥
    SecretKey secretKey = generateAESKey();
    String s = secretKeyToString(secretKey);
    System.out.println(s);

    // 使用密钥加密文本
    String encryptedText = encryptAES(originalText, s);
    System.out.println("Encrypted Text: " + encryptedText);

    // 使用同一个密钥解密文本
    String decryptedText = decryptAES(encryptedText, s);
    System.out.println("Decrypted Text: " + decryptedText);
  }

}
